<?php

namespace App\Http\Controllers;

use App\Models\NwYbzYptUserinfo;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Schema;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Log;
use Prophecy\Doubler\Generator\Node\ReturnTypeNode;

class NwYbzYptUserinfoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


    public function index(Request $request)
    {
        return "index";
    }

    // 一本账查询
    public function search_ybz(Request $request)
    {
        // 默认查询所有类型，或根据请求参数指定类型
        $resourceType = $request->input('resourceTypeTbale', 'YptUserinfo');

        // 支持的资源类型列表
        $supportedTypes = ['YptUserinfo'];

        // 确保请求的资源类型合法
        if (!in_array($resourceType, $supportedTypes) && $resourceType !== 'all') {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }

        // 设置每页显示的数量
        $perPage = $request->input('per_page', 10);

        // 初始化查询条件
        $queryParams = $request->except(['page', 'per_page', 'resourceTypeTbale', 'resource_name']);

        //获取zyj表中所有数据
        //$zyjData = NwYbzYjybz::all()->keyBy('manufacturer');
        // 获取 resource_name 查询参数
        $resourceName = $request->input('resource_name');

        $modelClass = "App\Models\NwYbz{$resourceType}";
        $query = (new $modelClass)::query();

        // 如果是查询所有类型
        if ($resourceName) {
            $results = collect(); // 初始化一个空的 Collection 对象来收集所有查询结果
            $total = 0; // 初始化总条目数
            $currentPage = LengthAwarePaginator::resolveCurrentPage(); // 获取当前页码

            $universalSearchValue = $request->input('resource_name');

            if ($universalSearchValue) {
                // 创建模型实例
                $modelInstance = new $modelClass();
                // 获取模型的文本类型字段名
                $textFields = Schema::getColumnListing($modelInstance->getTable()); // 注意这里使用实例
                $textFields = array_filter($textFields, function ($field) use ($modelInstance, $universalSearchValue) { // 传递$modelInstance 和 $universalSearchValue
                    return in_array(Schema::getColumnType($modelInstance->getTable(), $field), ['string', 'text']);
                });
                // 对所有文本字段添加模糊查询条件
                foreach ($textFields as $field) {
                    $query->orWhere($field, 'like', '%' . $universalSearchValue . '%');
                }
            } else {
                // 应用筛选条件
                foreach ($queryParams as $key => $value) {
                    $query->where($key, 'like', '%' . $value . '%');
                }
            }

            // 获取当前类型的结果
            $typeResults = $query->get();

            // 更新总条目数
            $total += $typeResults->count();
            //$results = $typeResults;
            // 合并当前类型的结果到总结果集中
            $results = $results->merge($typeResults);



            // 对所有结果进行分页处理
            $currentResults = $results->slice(($currentPage - 1) * $perPage, $perPage)->values();
            $pagedResults = new LengthAwarePaginator($currentResults, $total, $perPage, $currentPage, [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
            ]);


            // 构建统一的分页响应
            $meta = [
                'current_page' => $pagedResults->currentPage(),
                'last_page' => $pagedResults->lastPage(),
                'per_page' => $pagedResults->perPage(),
                'total' => $pagedResults->total(),
            ];

            return response()->json([
                'data' => $pagedResults->items(),
                'meta' => $meta,
            ]);
        } else {
            // 如果是单一类型查询
            // $modelClass = "App\Models\NwYbz{$resourceType}";
            // $query = (new $modelClass)::query();

            // 应用筛选条件
            foreach ($queryParams as $key => $value) {
                $query->where($key, 'like', '%' . $value . '%');
            }

            // 分页执行查询
            $pagedResults = $query->paginate($perPage);

            // 构建响应数据
            //$results = $pagedResults->items();
            // 构建响应数据并添加 resource_name
            $results = $pagedResults->items();
        }

        $meta = [
            'current_page' => $pagedResults->currentPage(),
            'last_page' => $pagedResults->lastPage(),
            'per_page' => $pagedResults->perPage(),
            'total' => $pagedResults->total(),
        ];

        return JsonResponse::fromJsonString(json_encode([
            'data' => $results,
            'meta' => $meta,
        ]));
    }

    // 
    public function ybzCurd(Request $request)
    {
        $resourceType = $request->input('resourceTypeTbale');
        $supportedTypes = ['YptUserinfo'];

        if (!in_array($resourceType, $supportedTypes)) {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }

        $modelClass = "App\Models\NwYbz{$resourceType}";

        $data = $request->except('resourceTypeTbale');

        $model = new $modelClass();
        foreach ($data as $key => $value) {
            $model->$key = $value;
        }
        $model->save();

        return response()->json(['message' => 'Resource created successfully'], 201);
    }

    //编辑接口
    public function ybzEdit(Request $request)
    {
        // 从请求体中获取所有数据
        $requestData = $request->json()->all();

        // 确保请求体中有数据
        if (empty($requestData)) {
            return response()->json(['message' => 'No request data found'], 400);
        }

        // 提取resourceTypeTbale
        $resourceType = $requestData['resourceTypeTbale'] ?? null;

        $supportedTypes = ['YptUserinfo'];

        // 验证resourceTypeTbale是否有效
        if (!in_array($resourceType, $supportedTypes)) {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }

        // 获取ID
        $id = $requestData['id'] ?? null;

        // 确保ID存在
        if (!$id) {
            return response()->json(['message' => 'Missing ID for editing'], 400);
        }

        // 移除resourceTypeTbale和id，准备更新的数据
        unset($requestData['resourceTypeTbale'], $requestData['id']);

        // 根据resourceTypeTbale确定模型类
        $modelClass = "App\Models\NwYbz{$resourceType}";

        // 使用主键查找记录
        $model = $modelClass::find($id);
        if (!$model) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        // 更新数据
        foreach ($requestData as $key => $value) {
            $model->$key = $value;
        }

        // 保存更新并响应结果
        if ($model->save()) {
            return response()->json(['message' => 'Resource updated successfully'], 200);
        } else {
            return response()->json(['message' => 'Failed to update the resource'], 500);
        }
    }

    //删除接口
    public function ybzDelete(Request $request)
    {
        $resourceType = $request->input('resourceTypeTbale');
        $id = $request->input('id');
        $supportedTypes = ['YptUserinfo'];

        if (!in_array($resourceType, $supportedTypes)) {
            return response()->json(['message' => 'Invalid resource type'], 400);
        }

        $modelClass = "App\Models\NwYbz{$resourceType}";

        try {
            // 使用模型类删除记录
            $deleted = $modelClass::destroy($id);

            if ($deleted) {
                return response()->json(['message' => 'Resource deleted successfully'], 200);
            } else {
                return response()->json(['message' => 'Resource not found'], 404);
            }
        } catch (\Exception $e) {
            // 记录日志或处理异常
            \Log::error($e);
            return response()->json(['message' => 'Deletion failed'], 500);
        }
    }
}
